<template>
  <div>
    <NormalForm :enumOpt="enumOpt" :formList="formList" :operateForm="queryForm" pageTitle="客户价值分析"
                @handleQuery="handleQuery" @handleReset="handleReset" @selectDateType="selectDateType"
    ></NormalForm>
    <div class="g-card">
      <el-tabs v-model="activeTab" @tab-click="handleQuery">
        <el-tab-pane label="存量客户" name="1"></el-tab-pane>
        <el-tab-pane label="增量客户" name="2"></el-tab-pane>
      </el-tabs>
      <template v-loading="loading">
        <div id="echart" class="echart"></div>
        <div class="table">
          <el-table :data="echartsList1" style="width: calc(100% - 80px); margin: 12px 40px">
            <el-table-column align="center" prop="name">
              <template slot="header">
                <div>客户价值等级<i class="el-icon-info" style="margin-left: 6px" @click="visible = true"></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="人数（人）" prop="showPnum"></el-table-column>
            <el-table-column align="center" label="客户占比" prop="showBnum"></el-table-column>
          </el-table>
        </div>
      </template>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="visible"
      append-to-body
      title="客户价值等级"
      width="650px"
    >
      <el-table :data="activeTab == '1' ? gradeTable1 : gradeTable2" width="600px">
        <el-table-column :label="activeTab == '1' ? '存量客户等级评分指标':'增量客户价值等级'" align="center"
                         prop="name"
        ></el-table-column>
        <el-table-column align="center" label="分值" prop="grade"></el-table-column>
      </el-table>
      <el-table :data="gradeList" width="600px">
        <el-table-column :label="activeTab == '1' ? '存量客户等级评分指标': '增量客户等级评分指标'" align="center">
          <el-table-column
            align="center"
            label="意向度"
            prop="IN"
          >
          </el-table-column>
          <el-table-column
            v-if="activeTab == '1'"
            align="center"
            label="客单价"
            prop="PC"
          >
          </el-table-column>
          <el-table-column
            align="center"
            label="购买力"
            prop="PP"
          >
          </el-table-column>
          <el-table-column
            align="center"
            label="活跃度"
            prop="AP"
          >
          </el-table-column>
          <el-table-column
            align="center"
            label="各指标分值"
            prop="grade"
          >
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { parseTime } from '@/utils/common'
import { getAllWeUser } from '@/api/customer/customerManage'

export default {
  name: 'customerValueAnalysis',
  data() {
    return {
      activeTab: '1',
      queryForm: {
        dateType: '0',
        dateRange: null,
        deptId: null,
        createCode: null,
        insuranceType: null
      },
      formList: [
        {
          label: '渠道',
          value: '',
          prop: 'insuranceType',
          type: 'SELECT',
          emunName: 'insuranceList'
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createCode',
          type: 'SELECT',
          emunName: 'creatorList'
        },
        {
          label: '',
          value: '',
          prop: 'dateType',
          type: 'SPECIAL_SELECT',
          emunName: 'dateTypeList'
        },
        {
          label: '',
          value: null,
          prop: 'dateRange',
          type: 'SPECIAL_DATE',
          emunName: '',
          aboutProp: 'dateType',
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now()
            }
          }
        }
      ],
      enumOpt: {
        insuranceList: [],
        creatorList: [],
        dateTypeList: [
          { dictLabel: '自然日', dictValue: '0' },
          { dictLabel: '自然周', dictValue: '1' },
          { dictLabel: '自然月', dictValue: '2' },
          { dictLabel: '自然年', dictValue: '3' }
        ]
      },
      echartsList: [],
      echartsList1: [],
      axisList: [],
      loading: false,
      visible: false,
      gradeTable1: [
        {
          name: '高净值客户',
          grade: '4'
        },
        {
          name: '重要发展客户',
          grade: '3'
        },
        {
          name: '重要保持客户',
          grade: '2'
        },
        {
          name: '重要挽留客户',
          grade: '1'
        },
        {
          name: '一般价值客户',
          grade: '0'
        },
        {
          name: '一般发展客户',
          grade: '-1'
        },
        {
          name: '一般保持客户',
          grade: '-2'
        },
        {
          name: '一般挽留客户',
          grade: '-3'
        },
        {
          name: '低价值客户',
          grade: '-4'
        }
      ],
      gradeTable2: [
        {
          name: '重要发展客户',
          grade: '3'
        },
        {
          name: '重要保持客户',
          grade: '2'
        },
        {
          name: '重要挽留客户',
          grade: '1'
        },
        {
          name: '一般价值客户',
          grade: '0'
        },
        {
          name: '一般发展客户',
          grade: '-1'
        },
        {
          name: '一般保持客户',
          grade: '-2'
        },
        {
          name: '一般挽留客户',
          grade: '-3'
        }
      ],
      gradeList: [
        {
          IN: '高',
          PC: '高',
          PP: '高',
          AP: '高',
          grade: '+1'
        },
        {
          IN: '中',
          PC: '中',
          PP: '中',
          AP: '中',
          grade: '0'
        },
        {
          IN: '低',
          PC: '低',
          PP: '低',
          AP: '低',
          grade: '-1'
        }
      ]
    }
  },
  watch: {
    'queryForm.deptId': {
      handler() {
        if (this.queryForm.deptId) {
          this.getAllWeUserInfo()
          this.queryForm.createCode = ''
        }

      }
    }
  },
  created() {
    this.getLabelList()
    this.selectDateType()
    this.handleQuery()
  },
  methods: {
    getLabelList() {
      // 渠道
      this.getDicts('insurance_type').then((res) => {
        if (res.code === 200) {
          this.enumOpt.insuranceList = res.data
        }
      })
    },
    getAllWeUserInfo() {
      this.enumOpt.creatorList = []
      const params = {
        deptId: this.queryForm.deptId,
        userName: ''
      }
      getAllWeUser(params).then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.enumOpt.creatorList.push({
              dictLabel: item.userName,
              dictValue: item.userId
            })
          })
        }
      })
    },
    selectDateType() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}')
      let endTime = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
      if (this.queryForm.dateType === '0') {
        this.queryForm.dateRange = [startTime, endTime]
      } else {
        this.queryForm.dateRange = startTime
      }
    },
    //展示图表
    getEcharts() {
      this.loading = false
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById('echart'))
      // 指定图表的配置项和数据
      var option = {
        grid: {
          //设置图表四周留白间距
          top: '2%',
          right: '1%',
          bottom: '4%',
          left: '4%'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false, //设置x轴两边的留白
          axisTick: {
            //x轴刻度尺
            show: false
          },
          show: false,
          axisLine: {
            //x轴线条颜色
            lineStyle: {
              color: '#999'
            }
          }
        },
        yAxis: {
          type: 'value',
          max: 100, //最大刻度值
          interval: 20, //刻度值间隔值
          show: false,
          splitLine: {
            //网格线
            show: false //关闭网格线
          },
          axisLine: {
            //y轴线条颜色
            show: true,
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false,
            alignWithLabel: false
          }
        },
        tooltip: {
          trigger: 'axis',
          showContent: false // 是否显示提示框浮层，默认显示
        },
        series: [
          {
            data: this.echartsList,
            label: {
              show: true,
              formatter: function(params) {
                let loading =
                  '人数' + '\n' + params.data.showPnum + '\n\n' + params.data.name + '\n' + params.data.showBnum
                return loading
              },
              position: ['30px', '-80px']
            },
            show: true,
            type: 'line',
            smooth: true, //面积图改成弧形状
            lineStyle: {
              width: 0, //外边线宽度
              color: 'red' //外边线颜色
            },
            showSymbol: true, //去除面积图节点圆
            symbol: 'circle',
            symbolSize: [0.01, 0.01],
            itemStyle: {
              color: '#082aff',
              zIndex: '999'
            },
            markLine: {
              symbol: ['none', 'none'],
              label: { show: false },
              // itemStyle:{
              //   normal:{
              lineStyle: {
                type: 'dashed',
                color: '#eee',
                zIndex: '-999'
              },
              //   },
              // },
              data: this.axisList
            },
            areaStyle: {
              //区域填充渐变颜色
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(8, 42, 255, 1)' // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(8, 42, 255, 0.2)' // 100% 处的颜色
                  }
                ],
                global: false // 缺省为 false
              }
            }
          }
        ]
      }
      // 使用刚指定的配置项和数据显示图表。
      this.$nextTick(() => {
        myChart.setOption(option)
      })
    },
    //列表查询
    handleQuery() {
      // this.loading = true;
      // let obj = this.reassembly();
      // const params = {
      //   dateType: obj.dateType,
      //   startDate: obj.startTime,
      //   endDate: obj.endTime,
      //   deptId: this.queryForm.deptId ? [this.queryForm.deptId] : [],
      //   userId: this.queryForm.createCode || '',
      //   insuranceType: this.queryForm.insuranceType || '',
      //   userType: this.activeTab
      // };
      // customerValue(params).then(res => {
      //   this.axisChange();
      //   this.echartsList = res.data;
      //   this.echartsList.forEach(item => {
      //     item.showPnum = item.value;
      //     item.showBnum = item.proportion;
      //     item.value = Number(item.showBnum.replace('%', '')) / 1.6;
      //   })
      //   const arr = res.data;
      //   let newArr = arr.slice(0, arr.length);
      //   newArr.pop();
      //   this.echartsList1 = newArr;
      //   this.getEcharts();
      // }).catch(() => {
      // })
      this.axisChange()
      let getData = new Array()
      if (this.activeTab == '1') {
        getData = [
          {
            'name': '低价值客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          },
          {
            'name': '一般挽留客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          },
          {
            'name': '一般保持客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          },
          {
            'name': '一般发展客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          },
          {
            'name': '一般价值客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          },
          {
            'name': '重要挽留客户',
            'value': 2,
            'proportion': '15.38%',
            'count': 2
          },
          {
            'name': '重要保持客户',
            'value': 3,
            'proportion': '23.08%',
            'count': 3
          },
          {
            'name': '重要发展客户',
            'value': 2,
            'proportion': '15.38%',
            'count': 2
          },
          {
            'name': '高净值客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          },
          {
            'name': '高净值客户',
            'value': 1,
            'proportion': '7.69%',
            'count': 1
          }
        ]
      } else {
        getData = [
          {
            'name': '一般挽留客户',
            'value': 18,
            'proportion': '11.76%',
            'count': 18
          },
          {
            'name': '一般保持客户',
            'value': 36,
            'proportion': '23.52%',
            'count': 36
          },
          {
            'name': '一般发展客户',
            'value': 29,
            'proportion': '18.95%',
            'count': 29
          },
          {
            'name': '一般价值客户',
            'value': 17,
            'proportion': '11.11%',
            'count': 17
          },
          {
            'name': '重要挽留客户',
            'value': 5,
            'proportion': '3.27%',
            'count': 5
          },
          {
            'name': '重要保持客户',
            'value': 22,
            'proportion': '14.38%',
            'count': 22
          },
          {
            'name': '重要发展客户',
            'value': 26,
            'proportion': '16.99%',
            'count': 26
          },
          {
            'name': '重要发展客户',
            'value': 26,
            'proportion': '16.99%',
            'count': 26
          }
        ]
      }
      this.echartsList = getData
      this.echartsList.forEach(item => {
        item.showPnum = item.value
        item.showBnum = item.proportion
        item.value = Number(item.showBnum.replace('%', '')) / 1.6
      })
      const arr = getData
      let newArr = arr.slice(0, arr.length)
      newArr.pop()
      this.echartsList1 = newArr
      window.setTimeout(() => {
        this.getEcharts()
      }, 1000)
    },
    handleReset() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}')
      let endTime = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
      this.enumOpt.creatorList = []
      this.queryForm = {
        dateType: '0',
        dateRange: [startTime, endTime],
        deptId: null,
        createCode: null,
        insuranceType: null
      }
      this.handleQuery()
    },
    // 组装startTime和endTime入参
    reassembly() {
      let startTime = null, endTime = null, dateType = null
      let selectDate = this.queryForm.dateRange
      if (selectDate) {
        if (this.queryForm.dateType === '0') {
          dateType = 'DAY' // 日
          startTime = selectDate[0]
          endTime = selectDate[1]
        } else if (this.queryForm.dateType === '1') {
          dateType = 'DAY' // 周
          startTime = parseTime(new Date(new Date(selectDate).getTime() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
          endTime = parseTime(new Date(new Date(selectDate).getTime() + 5 * 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
        } else if (this.queryForm.dateType === '2') {
          dateType = 'MONTH' // 月
          startTime = selectDate
          const temp = selectDate.split('-')
          let str = +temp[1] + 1
          temp[1] = temp[1] < 9 ? '0' + str : str
          if (temp[1] === 13) {
            temp[1] = '01'
            temp[0] = +temp[0] + 1
          }
          endTime = temp.join('-')
        } else if (this.queryForm.dateType === '3') {
          dateType = 'YEAR' // 年
          startTime = selectDate
          const temp = selectDate.split('-')
          temp[0] = +temp[0] + 1
          endTime = temp.join('-')
        }
      }
      return { startTime, endTime, dateType }
    },
    //echarts线条
    axisChange() {
      if (this.activeTab == '1') {
        this.axisList = [
          { xAxis: 0 },
          { xAxis: 1 },
          { xAxis: 2 },
          { xAxis: 3 },
          { xAxis: 4 },
          { xAxis: 5 },
          { xAxis: 6 },
          { xAxis: 7 },
          { xAxis: 8 },
          { xAxis: 9 },
          { xAxis: 10 }
        ]
      } else if (this.activeTab == '2') {
        this.axisList = [
          { xAxis: 0 },
          { xAxis: 1 },
          { xAxis: 2 },
          { xAxis: 3 },
          { xAxis: 4 },
          { xAxis: 5 },
          { xAxis: 6 },
          { xAxis: 7 },
          { xAxis: 8 }
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

#echart {
  padding: 10px;
  width: 96%;
  height: 300px;
}
</style>
